package com.yuyou.weixin.service.impl;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yuyou.weixin.bean.ResBoolSimpleInfo;
import com.yuyou.weixin.common.WexinException;
import com.yuyou.weixin.message.CaptchaMess;
import com.yuyou.weixin.vo.MessageResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.weixin.entity.CommSmsVerCode;
import com.yuyou.weixin.service.HttpClientService;
import com.yuyou.weixin.service.ICommKeyConfigService;
import com.yuyou.weixin.service.ICommSmsVerCodeService;
import com.yuyou.weixin.service.ISmsService;
import com.yuyou.weixin.util.MD5Util;

/**
 * Sms 表数据服务层接口实现类
 */
@Service
public class SmsServiceImpl implements ISmsService {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ICommKeyConfigService commKeyConfigService;

	@Autowired
	private ICommSmsVerCodeService commSmsVerCodeService;

	@Autowired
	private HttpClientService httpClientService;

	@Value("${message.url}")
	private String messageUrl;

	@Value("${message.key}")
	private String messageKey;

	@Override
	@Transactional
	public MessageResult sendCode(String phoneNo, String type, String content) {

        MessageResult sendResult =null  ;
		try {
			Map<String, String> params= new HashMap<>();
			params.put("content", content);
			params.put("token", MD5Util.md5Hex(phoneNo+messageKey));
			params.put("phoneNo", phoneNo);
			String result = httpClientService.client(messageUrl,params);
			if(result != null){
				MessageResult mr = JSON.parseObject(result,new TypeReference<MessageResult>() {});
				if(mr != null){
					sendResult = mr;
				}
			}
			logger.info(String.format("开启短信接口,手机号码是%s,短信内容是%s,接口返回结果是%s", phoneNo,content,result));
		} catch (Exception e) {
            logger.error("sms not available", e);
		}


		return sendResult;
	}

	@Override
	@Transactional
	public ResBoolSimpleInfo<String> validate(String phoneNo, String type, String code) {
        ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
		/*CommKeyConfig sms_open = commKeyConfigService
				.selectByDataKey("sms_open");

		if (sms_open == null || sms_open.getDataKey().equals("0")) {
			return true;
		}*/

		CommSmsVerCode commSmsVerCode = commSmsVerCodeService
				.selectLastByMobileAndTypeAndCode(phoneNo, type, code);
		if (commSmsVerCode == null||commSmsVerCode.getVerTime()>3 || !code.equals(commSmsVerCode.getCode())
                || (new Date().getTime() - commSmsVerCode.getCreateTime()
                .getTime()) > 5 * 60 * 1000){
            res.setSuccess(false);
            res.setMessage(CaptchaMess.ERR_MESSAGE_EXPIRE);
		}else{
            res.setSuccess(true);
		}
		if(commSmsVerCode !=null){
			//更新校验次数
			CommSmsVerCode up=new CommSmsVerCode();
			up.setId(commSmsVerCode.getId());
			up.setVerTime(commSmsVerCode.getVerTime()+1);
			commSmsVerCodeService.updateByPrimaryKeySelective(up);		

		}
		return res;
	}

}